import random
from string import Template
import allure
import requests
from loguru import logger

from settings import upload_imgs


class HandleRequests:

    def __init__(self):
        # 所有请求固定的内容
        self.header = {"Accept-Language": "zh-CN"}

    @allure.step("===发送请求===")
    def send_requests(self, method, url, json=None, files=None, token=None):
        # 处理请求头
        headers = self.__pre_header(token)
        # 处理files
        files = self.__pre_files(files)
        # 处理json
        json = self.__pre_json(json)
        # 发送请求
        logger.info("===测试开始===")
        logger.info(f"请求方法：{method}")
        logger.info(f"请求url：{url}")
        logger.info(f"请求header:{headers}")
        logger.info(f"请求json：{json}")
        logger.info(f"请求files:{files}")

        resp = requests.request(method, url, headers=headers, json=json, files=files)

        logger.info(f"响应状态码：{resp.status_code}")
        logger.info(f"响应结果：{resp.text}")
        return resp

    def __pre_header(self, token):
        if token:
            logger.info("本次请求需要鉴权")
            # self.header.update({"Authorization": f"bearer{token}"})
            headers = {"Authorization": f"bearer{token}"}
            headers.update(self.header)
            return headers

        else:
            logger.info("本次请求不需要鉴权")
            return self.header

    def __pre_files(self, files):
        if files:
            # 随机获取一个img
            image_name, image_path, image_type = upload_imgs[random.randint(0, len(upload_imgs) - 1)]
            # 调用string.Template替换files字段中的值
            template = Template(files)
            files = template.substitute(image_name=image_name, image_path=image_path, image_type=image_type)
            # 去掉“”
            files = eval(files)
        return files

    def __pre_json(self, json_str):
        if json_str:
            json_dict = eval(json_str)
            return json_dict
        else:
            return json_str
